/****************************************************************
 *Author:       zxx
 *UnityVersion：2019.4.1f1
 *Date:         2020/07/29 17:39:42
 *Description:    
*****************************************************************/
using Prime31;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour {


    private Vector3 ori;
    // movement config
    public float gravity = -25f;
    public float runSpeed = 8f;
    public float groundDamping = 20f; // how fast do we change direction? higher means faster
    public float inAirDamping = 5f;
    public float jumpHeight = 3f;

    [HideInInspector]
    private float normalizedHorizontalSpeed = 0;

    private CharacterController2D _controller;
    private Animator _animator;
    private RaycastHit2D _lastControllerColliderHit;
    private Vector3 _velocity;

    private AudioSource source;
    public AudioClip jump,  hurt;

    private bool jumping;

    void Awake()
    {
        _animator = GetComponent<Animator>();
        _controller = GetComponent<CharacterController2D>();

        _controller.onControllerCollidedEvent += onControllerCollider;

        normalizedHorizontalSpeed = 0;

        ori = transform.position;

        source = GetComponent<AudioSource>();
       

    }

    private void OnEnable()
    {
        EventCenter.AddListener(EventDefine.PlayerJump, Jump);
        EventCenter.AddListener(EventDefine.PlayerLeftDown, LeftDown);
        EventCenter.AddListener(EventDefine.PlayerLeftUp, LeftUp);
        EventCenter.AddListener(EventDefine.PlayerRightDown, RightDown);
        EventCenter.AddListener(EventDefine.PlayerRightUp, RightUP);
    }

    private void OnDisable()
    {
        EventCenter.RemoveListener(EventDefine.PlayerJump, Jump);
        EventCenter.RemoveListener(EventDefine.PlayerLeftDown, LeftDown);
        EventCenter.RemoveListener(EventDefine.PlayerLeftUp, LeftUp);
        EventCenter.RemoveListener(EventDefine.PlayerRightDown, RightDown);
        EventCenter.RemoveListener(EventDefine.PlayerRightUp, RightUP);
    }

    private void LeftDown()
    {
        normalizedHorizontalSpeed = -1;
        if (transform.localScale.x > 0f)
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);

        if (_controller.isGrounded)
            _animator.Play(Animator.StringToHash("PlayerRun"));
    }

    private void LeftUp() {
        normalizedHorizontalSpeed = 0;
        if (_controller.isGrounded)
            _animator.Play(Animator.StringToHash("PlayerIdle"));
    }

    private void RightDown()
    {
        
        normalizedHorizontalSpeed = 1;
        if (transform.localScale.x < 0f)
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);

        if (_controller.isGrounded)
            _animator.Play(Animator.StringToHash("PlayerRun"));

    }

    private void RightUP()
    {
        normalizedHorizontalSpeed = 0;
        if (_controller.isGrounded)
            _animator.Play(Animator.StringToHash("PlayerIdle"));
    }


    private void OnDestroy()
    {
      

    }

    #region Event Listeners

    void onControllerCollider(RaycastHit2D hit)
    {
   
        if (hit.normal.y == 1f)
            return;

    }
    #endregion

   


    void Update()
    {
        if (GameMananger.Instance.isGameOver) return;
        if (_controller.isGrounded)
        {
            _velocity.y = 0;

            jumping = false;
        }

        if (normalizedHorizontalSpeed ==1)
        {
            normalizedHorizontalSpeed = 1;
            if (transform.localScale.x < 0f)
                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);

            if (_controller.isGrounded)
                _animator.Play(Animator.StringToHash("PlayerRun"));
        }
        else if (normalizedHorizontalSpeed == -1)
        {
            normalizedHorizontalSpeed = -1;
            if (transform.localScale.x > 0f)
                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);

            if (_controller.isGrounded)
                _animator.Play(Animator.StringToHash("PlayerRun"));
        }
        else
        {
            normalizedHorizontalSpeed = 0;

        }

       
        var smoothedMovementFactor = _controller.isGrounded ? groundDamping : inAirDamping; 
        _velocity.x = Mathf.Lerp(_velocity.x, normalizedHorizontalSpeed * runSpeed, Time.deltaTime * smoothedMovementFactor);


        _velocity.y += gravity * Time.deltaTime;


        _controller.move(_velocity * Time.deltaTime);


        _velocity = _controller.velocity;

        GameMananger.Instance.gameOverTimer -= Time.deltaTime;
        if (GameMananger.Instance.gameOverTimer <= 0)
        {
            GameMananger.Instance.isGameOver = true;
            GameMananger.Instance.gameOverTimer = 0;
            //this.enabled = false;
            source.PlayOneShot(hurt);
            _animator.Play(Animator.StringToHash("PlayerHurt"));
            this.enabled = false;
            Invoke("Restart", 2f);
        }

    }



    private void Jump()
    {
 
        if (jumping == false && GameMananger.Instance.isGameOver==false)
        {
            //normalizedHorizontalSpeed = 1;
            //GameMananger.Instance.isStarted = true;
            Debug.Log("Jump");
            _animator.Play(Animator.StringToHash("PlayerJump"));
            //tailRender.enabled = true;
            source.PlayOneShot(jump);
            _velocity.y = Mathf.Sqrt(2f * jumpHeight * -gravity);
            _controller.move(_velocity * Time.deltaTime);
            jumping = true;
            EventCenter.Broadcast(EventDefine.ReocketSpawn);
        }
       

    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        //if (GameMananger.Instance.isStarted){
            if (collision.tag == "Enemy")
            {          
                if (_velocity.y < -2)
                {
                    //EventCenter.Broadcast(EventDefine.EnemyDying);
                    collision.GetComponent<EnemyController>().Dying();
                }
                else
                {
                    if (GameMananger.Instance.isGameOver == false && GameMananger.Instance.invincible==false)
                    {
                        GameMananger.Instance.isGameOver = true;
                        //this.enabled = false;
                        source.PlayOneShot(hurt);
                        _animator.Play(Animator.StringToHash("PlayerHurt"));
                    
                        this.enabled = false;
                        Debug.Log("碰撞到敌人");

                        Invoke("Restart", 2f);
                    }

                }
                

            }
            else if (collision.tag == "DeathTrigger")
            {

                Invoke("Restart", 1);
            }
            else if (collision.tag == "Rocket" && GameMananger.Instance.invincible == false)
            {
                GameMananger.Instance.isGameOver = true;
                collision.GetComponent<Animator>().Play(Animator.StringToHash("RocketExplore"));
                _animator.Play(Animator.StringToHash("PlayerHurt"));
                this.enabled = false;
                source.PlayOneShot(hurt);
                Invoke("Restart", 1);

            }else if(collision.tag == "FinallyTrigger")
            {
            //GameMananger.Instance.isStarted = false;
                EventCenter.Broadcast(EventDefine.SuccessPanelShow);
                GameMananger.Instance.isGameOver = true;
                _animator.Play(Animator.StringToHash("PlayerVictor"));
                this.enabled = false;
                Invoke("Restart", 5f);


            }      
    }


    private void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);

        //GameMananger.Instance.diamontCount = 0;
        //GameMananger.Instance.roadCount = 0;
        //GameMananger.Instance.isStarted = false;
        //GameMananger.Instance.isGameOver = false;

        //normalizedHorizontalSpeed = 0;
        //transform.position = ori;
        //_animator.Play(Animator.StringToHash("PlayerSpawn"));
    }
}

